﻿// Copyright 2013 Ronald Schlenker, www.technewlogic.de.
// 
// This file is part of Byond.
// 
// Byond is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
// 
// Byond is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with Byond.  If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Linq;

namespace Byond.HostObjects
{
	public class CallbackController<T>
	{
		private CallbackControl<T>[] _callbackControls = new CallbackControl<T>[0];

		internal CallbackControl Register(Action<T> callback)
		{
			return Register((arg, c) => callback(arg));
		}

		internal CallbackControl Register(Action<T, CallbackControl> callback)
		{
			var callbackControl = new CallbackControl<T>(callback);
			_callbackControls = _callbackControls.Add(callbackControl);
			return callbackControl;
		}

		internal void Raise(T args)
		{
			var callbackControls = _callbackControls;
			var needsGarbageCollection = false;

			foreach (var it in callbackControls)
			{
				if (it.StopRequest)
				{
					needsGarbageCollection = true;
					continue;
				}

				it.Raise(args);

				// TODO: IsOneTime
				//if (it.IsOneTime)
				//{
				//    it.Stop();
				//    needsGarbageCollection = true;
				//}
			}

			if (needsGarbageCollection)
			{
				foreach (var it in callbackControls)
				{
					if (it.StopRequest)
						_callbackControls = _callbackControls.Remove(it);
				}
			}
		}

		internal void Clear()
		{
			_callbackControls = new CallbackControl<T>[0];
		}
	}
}
